using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NutriStat.Data;
//using Excel = Microsoft.Office.Interop.Excel;


namespace NutriStat
{
    public partial class GridViewForm : FormBase
    {
        private NutriStat.Data.IDbDriver db;
        private string m_sSelection;
        private string m_sTableName;
        private bool m_bIsFindWindow;
        private FormMainMenu m_fMainMenu;
        private int m_iId;

        public GridViewForm()
        {
            InitializeComponent();           
        }

        // This is our custom constructor. We have to pass in
        // the ID value, table name, and file name for obvious reasons. The First Name and Last Name
        // strings get put at the top of the form window. This way we don't have to bring those columns
        // up in the grid view itself and waste space.
        public GridViewForm(NutriStat.Data.IDbDriver database, int id, string tableName)
        {
            InitializeComponent();

            db = database;

            // Set the titlebar text; make it look like Epi 3's NutStat module
            //this.Text = id + " - " + lastName + ", " + firstName;            
            
            //m_sIdNo = id.ToString();
            m_iId = id;
            m_sTableName = tableName;
            SetFindWindow(false);
        }

        // This is another custom constructor used for the custom export preview.        
        public GridViewForm(string connection, string connectionType, string tableName, string selection)
        {
            InitializeComponent();

            // Set the titlebar text; make it look like Epi 3's NutStat module
            this.Text = SharedStrings.EXPORT_PREVIEW;

            // Assign our internal class vars with the stuff that was passed in as parameters                        
            SetSelection(selection);
            SetFindWindow(false);
        }

        // This is another custom constructor used for the find function.      
        public GridViewForm(string connection, string connectionType, string tableName, string selection, bool isFindWindow, FormMainMenu mainMenu)
        {
            InitializeComponent();

            // Set the titlebar text; make it look like Epi 3's NutStat module
            this.Text = SharedStrings.RESULTS;

            // Assign our internal class vars with the stuff that was passed in as parameters                        
            SetSelection(selection);
            SetFindWindow(isFindWindow);
            m_fMainMenu = mainMenu;
        }

        private void GridViewForm_Load(object sender, EventArgs e)
        {
            if (IsFindWindow())
            {
                exportToolStripMenuItem.Visible = false;
            }

            ConfigureFormControls();
                        
            string tableName = GetTableName();            
            
            DataTable dt = db.GetTableData(m_sTableName, "*", "fldIdNo, fldCurrentDate ASC");            
            dt.TableName = m_sTableName;
            
            Query selectQuery = db.CreateQuery("select * from " + m_sTableName + " where [fldIdNo] = @Id");
                selectQuery.Parameters.Add(new QueryParameter("@Id", DbType.Int32, m_iId));

            DataTable showtable = db.Select(selectQuery);           
            
            showtable.Locale = System.Globalization.CultureInfo.InvariantCulture;           

            bindingSourcePrimary.DataSource = showtable;

            // Add record count to the title bar if this is displaying
            // the results from a Find
            if (IsFindWindow())
            {
                int rows = showtable.Rows.Count;
                this.Text = this.Text + ": " + rows.ToString() + " records";
            }

            dataGridViewPrimary.ReadOnly = true;    // Don't let users modify anything!

            // Bind the data to the grid control
            dataGridViewPrimary.DataSource = bindingSourcePrimary;

            dataGridViewPrimary.Font = new Font("Verdana", 8.0f);

            // Downsize the columns as appropriate to their actual width
            // Without this, we get something like 'Edema' taking up a massive amount of width
            dataGridViewPrimary.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            dt.Dispose();
            showtable.Dispose();
            
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // --------------------------------------------------------------------------
        // Function: SetTableName (string)
        // Purpose: Sets the table name.
        // --------------------------------------------------------------------------
        public void SetTableName(string table)
        {
            m_sTableName = table;
        }

        // --------------------------------------------------------------------------
        // Function: GetTableName (void)
        // Purpose: Gets the table name.
        // --------------------------------------------------------------------------
        public string GetTableName()
        {
            return m_sTableName;
        }


        // --------------------------------------------------------------------------
        // Function: SetSelection (string)
        // Purpose: Sets the SELECT query
        // --------------------------------------------------------------------------
        public void SetSelection(string query)
        {
            m_sSelection = query;
        }

        // --------------------------------------------------------------------------
        // Function: GetSeletion (void)
        // Purpose: Gets the SELECT query
        // --------------------------------------------------------------------------
        public string GetSelection()
        {
            return m_sSelection;
        }


        // --------------------------------------------------------------------------
        // Function: SetFindWindow (string)
        // Purpose: Sets whether or not the window is a 'Find' grid.
        // --------------------------------------------------------------------------
        private void SetFindWindow(bool value)
        {
            m_bIsFindWindow = value;
        }

        // --------------------------------------------------------------------------
        // Function: IsFindWindow (void)
        // Purpose: Returns true if the window is a 'Find' grid, false if it is not.
        //      This is important, because if true, the user can double-click a grid
        //      entry and go to that record in the main NutriStat window; this also
        //      closes the Grid view.
        // --------------------------------------------------------------------------
        public bool IsFindWindow()
        {
            return m_bIsFindWindow;
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = saveFileDialogExport.ShowDialog();
            
            if (result == DialogResult.Cancel)
                return;

            string fileName = saveFileDialogExport.FileName;            
            
            if (fileName.Equals(string.Empty))
                return;

            try
            {
                /*
                Excel.Application excelApp;
                Excel.Workbook excelWorkbook;
                Excel.Worksheet excelWorksheet;
                object missing = System.Reflection.Missing.Value;

                excelApp = new Excel.ApplicationClass();
                excelWorkbook = excelApp.Workbooks.Add(missing);
                excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(1);
                
                if (!IsFindWindow() && GetSelection() == "")
                {
                    excelWorksheet.Cells[1, 1] = "fldCurrentDate";
                    excelWorksheet.Cells[1, 2] = "fldAge";
                    excelWorksheet.Cells[1, 3] = "fldEdema";
                    excelWorksheet.Cells[1, 4] = "fldRecumbent";
                    excelWorksheet.Cells[1, 5] = "fldInch";
                    excelWorksheet.Cells[1, 6] = "fldLbs";
                    excelWorksheet.Cells[1, 7] = "fldOzs";
                    excelWorksheet.Cells[1, 8] = "fldCDCHAC";
                    excelWorksheet.Cells[1, 9] = "fldCDCHAZ";

                    excelWorksheet.Cells[1, 10] = "fldCDCWHC";
                    excelWorksheet.Cells[1, 11] = "fldCDCWHZ";
                    excelWorksheet.Cells[1, 12] = "fldCDCWAC";
                    excelWorksheet.Cells[1, 13] = "fldCDCWAZ";
                    excelWorksheet.Cells[1, 14] = "fldBMI";
                    excelWorksheet.Cells[1, 15] = "fldBMIC";
                    excelWorksheet.Cells[1, 16] = "fldBMIZ";
                }
                else
                {
                    excelWorksheet.Cells[1, 1] = "fldIdNo";
                    excelWorksheet.Cells[1, 2] = "fldCurrentDate";
                    excelWorksheet.Cells[1, 3] = "FKey";
                    excelWorksheet.Cells[1, 4] = "fldFirstName";
                    excelWorksheet.Cells[1, 5] = "fldLastName";
                    excelWorksheet.Cells[1, 6] = "fldSex";
                    excelWorksheet.Cells[1, 7] = "fldAge";
                    excelWorksheet.Cells[1, 8] = "fldBirthDate";
                    excelWorksheet.Cells[1, 9] = "fldEdema";

                    excelWorksheet.Cells[1, 10] = "fldRecumbent";
                    excelWorksheet.Cells[1, 11] = "fldNotes";
                    excelWorksheet.Cells[1, 12] = "fldCm";
                    excelWorksheet.Cells[1, 13] = "fldInch";
                    excelWorksheet.Cells[1, 14] = "fldKilos";
                    excelWorksheet.Cells[1, 15] = "fldLbs";
                    excelWorksheet.Cells[1, 16] = "fldOzs";
                    excelWorksheet.Cells[1, 17] = "fldCDCHAC";
                    excelWorksheet.Cells[1, 18] = "fldCDCWHC";
                    excelWorksheet.Cells[1, 19] = "fldCDCWAC";

                    excelWorksheet.Cells[1, 20] = "fldCDCHAZ";
                    excelWorksheet.Cells[1, 21] = "fldCDCWAZ";
                    excelWorksheet.Cells[1, 22] = "fldCDCWHZ";
                    excelWorksheet.Cells[1, 23] = "fldCDCFlag";
                    excelWorksheet.Cells[1, 24] = "fldcmMUAC";
                    excelWorksheet.Cells[1, 25] = "fldinMUAC";
                    excelWorksheet.Cells[1, 26] = "fldMUACAgeZ";
                    excelWorksheet.Cells[1, 27] = "fldMUACHeightZ";
                    excelWorksheet.Cells[1, 28] = "fldcmHCircum";
                    excelWorksheet.Cells[1, 29] = "fldinHCircum";

                    excelWorksheet.Cells[1, 30] = "fldHCircumC";
                    excelWorksheet.Cells[1, 31] = "fldHCircumZ";
                    excelWorksheet.Cells[1, 32] = "fldBMI";
                    excelWorksheet.Cells[1, 33] = "fldBMIC";
                    excelWorksheet.Cells[1, 34] = "fldBMIZ";
                    excelWorksheet.Cells[1, 35] = "fldCDCHAFlag";
                    excelWorksheet.Cells[1, 36] = "fldCDCWAFlag";
                    excelWorksheet.Cells[1, 37] = "fldCDCWHFlag";
                    excelWorksheet.Cells[1, 38] = "fldCDCBMIFlag";
                }

                int i = 0;
                int j = 0;

                for (i = 0; i <= dataGridViewPrimary.RowCount - 1; i++)
                {
                    for (j = 0; j <= dataGridViewPrimary.ColumnCount - 1; j++)
                    {
                        DataGridViewCell cell = dataGridViewPrimary[j, i];
                        excelWorksheet.Cells[i + 2, j + 1] = cell.Value;
                    }
                }

                excelWorkbook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                excelWorkbook.Close(true, missing, missing);
                excelApp.Quit();   
                 */
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            GC.Collect();
        }

        private void dataGridViewPrimary_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // We don't want the user double-clicking a row and loading that record into
            // the main window if this isn't showing the results from a 'find' operation.
            if (!IsFindWindow())
                return;
            
            try
            {
                // Create a data grid row and assign it the value of CurrentRow, which is the
                // currently-selected row.
                DataGridViewRow row = dataGridViewPrimary.CurrentRow;

                // Get our collection of cells, which should be all the cells in this row
                DataGridViewCellCollection cells = row.Cells;

                // The first two columns should always be the ID and the current date, so we
                // take those two values from our cell array and assign them to temp vars;
                // we need to do some conversions here as well.
                int id = Convert.ToInt32(cells[0].Value);                
                DateTime date = Convert.ToDateTime(cells[1].Value);

                m_fMainMenu.AssignDatabaseValues(false, false, id, true, date, true);                
            }
            catch (Exception ex)
            {
                // Catch our exception.
                MessageBox.Show(ex.ToString());
            }                        
        }

        /// <summary>
        /// Configures the form controls based on the user's preferences, as defined in the options.
        /// </summary>
        protected internal override void ConfigureFormControls()
        {
            this.Text = SharedStrings.GRID;
            fileToolStripMenuItem.Text = SharedStrings.MENU_FILE;
            exportToolStripMenuItem.Text = SharedStrings.MENU_FILE_EXPORT;
        }
    }
}